package com.dolittle.test;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AddView extends LinearLayout implements OnClickListener {

	private Context mContext;
	private TextView[] mTitle;
	private EditText[] mEdit;
	public static TextView mOutput;
	private Button mButtonAdd;
	private Button mButtonRemove;
	private WordList mList;

	public AddView(Context context,WordList list) {
		super(context);
		mContext = context;
		mList = list;
		init();
	}

	private void init() {
		mTitle = new TextView[2];
		mEdit = new EditText[2];
		mOutput = new TextView(mContext);
		mButtonAdd = new Button(mContext);
		mButtonAdd.setOnClickListener(this);
		mButtonAdd.setId(1);
		mButtonRemove = new Button(mContext);
		mButtonRemove.setOnClickListener(this);
		mButtonRemove.setId(2);

		for (int i = 0; i < 2; i++) {
			mTitle[i] = new TextView(mContext);
			mTitle[i].setId(i);
			mEdit[i] = new EditText(mContext);
			mEdit[i].setId(i);
		}
		mTitle[0].setHint("Swedish:");
		mEdit[0].setHint("Write in Swedish here");
		mTitle[1].setHint("Spanish:");
		mEdit[1].setHint("Write in Spanish here");

		mButtonAdd.setText("Add words");
		mButtonRemove.setText("Remove words");
		initViews();

	}

	private void initViews() {
		setOrientation(VERTICAL);

		addView(mTitle[0]);
		addView(mEdit[0]);
		addView(mTitle[1]);
		addView(mEdit[1]);
		addView(mButtonAdd);
		addView(mButtonRemove);
		addView(mOutput);
	}

	public void writeFile() {
		mList.writeFile();
	}

	@Override
	public void onClick(View v) {
		if (v instanceof Button) {
			Button b = (Button) v;
			if (b.getId() == 1) {
				boolean added = mList.addWord(mEdit[0].getText().toString(),
						mEdit[1].getText().toString());
				if (added) {
					mOutput.setText("Added: " + mEdit[0].getText().toString()
							+ " = " + mEdit[1].getText().toString());
				} else {
					mOutput.setText("Word already exists.");
				}
			} else if (b.getId() == 2) {
				boolean removed = mList.removeWord(mEdit[0].getText()
						.toString(), mEdit[1].getText().toString());
				if (removed) {
					mOutput.setText("Removed: " + mEdit[0].getText().toString()
							+ " = " + mEdit[1].getText().toString());
				} else {
					mOutput.setText("Word didn't exist.");
				}
			}
			mEdit[0].setText("");
			mEdit[1].setText("");
			writeFile();
		}
	}
}
